package com.cw.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import com.cw.starter.redis.helper.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.cw.demo.dao.model.UserDo;
import com.cw.demo.service.UserService;
import com.cw.starter.common.util.IdGenerator;
import com.cw.starter.mq.dto.MqMsgDto;
import com.cw.starter.mq.producer.MqMessageProducer;

import lombok.extern.slf4j.Slf4j;

/**
 * TODO
 *
 * @author chenw
 * @date 2021/7/26
 */
@RestController
@RequestMapping("")
@Slf4j
public class DemoController {
    @Value(value = "${userPassword:chenw}")
    private String userPassword;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MqMessageProducer mqMessageProducer;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisCache redisCache;
    @RequestMapping("/test")
    public void test() {
        String url = "http://localhost:10010/message";
        //设置header信息
        HttpHeaders headers = new HttpHeaders();
        String userName = "chenw";
        HttpEntity<String> entity = new HttpEntity<>(userName, headers);
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
        System.out.println(userPassword);
    }

    @RequestMapping("/hello")
    public void hello() {
        MqMsgDto mqMsgDto = new MqMsgDto();
        mqMsgDto.setMsgContent("hhhhh");
        mqMsgDto.setMsgSize(1111);
        mqMsgDto.setSerialNo(UUID.randomUUID()
            .toString());
        mqMsgDto.setTradeDate(new Date());
        mqMessageProducer.send("hrkj-topic", mqMsgDto);
    }

    @RequestMapping("/testRedisScan")
    public void testRedisScan() {
        Set<String> keys = redisCache.scanKeys("USER_*", 1000);
        log.info(keys.size() + "");
    }

    /**
     * 批量保存用户信息到分表中
     */
    @RequestMapping("/saveUser")
    public void saveUser() {
        List<UserDo> userDoList = new ArrayList<>();
        for (int i = 0; i < 100000000; i++) {
            UserDo userDo = new UserDo();
            userDo.setId(IdGenerator.nextId());
            userDo.setUserName("chenw" + i);
            userDo.setSex("0");
            userDo.setCreateTime(new Date());
            userDoList.add(userDo);
            if (i % 1000 == 0) {
                userService.saveBatch(userDoList);
                userDoList.clear();
            }
            i++;
        }
    }
}
